<template lang="pug">
  div
    div(v-if="flag")
      el-form(:model="formModel" :rules="newRules" ref="newPassword")
        el-form-item(label="密码" prop="password")
          el-input(v-model="formModel.password" type="password")
        el-form-item(label="确认密码" prop="confirmPassword")
          el-input(v-model="formModel.confirmPassword" type="password")
        el-form-item
          el-button(@click="submit") 提交
    div(v-if="sign")
      p 链接已失效
</template>

<script type="text/ecmascript-6">
  import
    FormModel from './model'
  import {loginUrl} from '../../config/global.toml'
  import Message from '../../common/message'

  export default {
    data() {
      var validatePassword = (rule, value, callback) => {
        if (value !== undefined && value !== null && value !== '') {
          let valTrim = value.replace(/^\s+|\s+$/g, '')
          let reg = /^[a-zA-Z0-9]+$/
          if (reg.test(valTrim)) {
            callback()
          } else {
            callback(new Error('密码中包含特殊字符，请输入正确的密码'))
          }
        }
      }
      var validatePasswordAgain = (rule, value, callback) => {
        if (value !== undefined && value !== null && value !== '') {
          let valTrim = value.replace(/^\s+|\s+$/g, '')
          if (valTrim === this.formModel.password) {
            callback()
          } else {
            callback(new Error('两次密码不一致'))
          }
        } else {
          callback(new Error('请输入重复密码'))
        }
      }
      return {
        sign: false,
        flag: true,
        acc: '',
        formModel: Object.assign({}, FormModel),
        newRules: {
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'},
            {min: 4, max: 8, message: '密码长度错误，请重新输入', trigger: 'blur'},
            {validator: validatePassword, trigger: 'blur'}
          ],
          confirmPassword: [
            {required: true, message: '请再次输入密码', trigger: 'blur'},
            {validator: validatePasswordAgain, trigger: 'blur'}
          ]
        }
        // name: 'NewPassword'
      }
    },
    mounted() {
      this.getUrl()
      this.getToken()
      this.formModel.id = this.$route.query.id
    },
    methods: {
      getUrl() {
        var name, value
        var str = decodeURIComponent(location.href) // 取得整个地址栏
        var num = str.indexOf('?')
        str = str.substr(num + 1) // 取得所有参数   stringvar.substr(start [, length ]
        var arr = str.split('&') // 各个参数放到数组里
        for (var i = 0; i < arr.length; i++) {
          num = arr[i].indexOf('=')
          if (num > 0) {
            name = arr[i].substring(0, num)
            value = arr[i].substr(num + 1)
            this[name] = value
          }
        }
      },
      getToken() {
        let _data = {
          'username': 'admin',
          'password': '123'
        }
        this.$http.request({
          method: 'POST',
          url: loginUrl,
          transformRequest: [(data) => {
            // Do whatever you want to transform the data
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            return ret
          }],
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          data: _data
        }).then(res => {
          if (res.data.success) {
            this.acc = res.data.access_token
            this.getValidate()
          }
        })
      },
      submit() {
        this.$refs.newPassword.validate((valid) => {
            if (valid) {
              this.axios.request({
                method: 'GET',
                url: 'camel/rest/training/course/getPassword',
                params: {
                  id: this.formModel.id,
                  password: this.formModel.password
                },
                headers: {
                  access_token: this.acc
                }
              }).then(res => {
                console.log('res----------------------:', res.data)
                Message.success(JSON.parse(res.data).msg)
                if (JSON.parse(res.data).msg === '修改成功') {
                  setTimeout(() => {
                    this.$router.push('/')
                  }, 4000)
                }
              })
            }
          }
        )
      },
      getValidate() {
        this.axios.request({
          method: 'GET',
          url: 'camel/rest/training/course/getValidate',
          params: {
            id: this.formModel.id
          },
          headers: {
            access_token: this.acc
          }
        }).then(res => {
          if (res.data === '链接已失效') {
            this.flag = false // 修改页面不显示
            this.sign = true // 显示链接已失效文字
          } else {
            this.flag = true
            this.sign = false
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
